package com.tianya.service.impl;

import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianya.domain.dto.LoginRequestDTO;
import com.tianya.domain.dto.RegisterDTO;
import com.tianya.domain.entity.User;
import com.tianya.domain.enums.AccountStatus;
import com.tianya.domain.enums.Message;
import com.tianya.domain.vo.LoginVO;
import com.tianya.domain.vo.UserVO;
import com.tianya.exception.CustomException;
import com.tianya.mapper.LoginMapper;
import com.tianya.service.LoginService;
import com.tianya.service.TeacherService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;

/**
 * @author TianYaGuoKe
 * @date 2025/5/24 19:10
 * @description LoginServiceImpl
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, User> implements LoginService {

    @Resource
    private TeacherService teacherService;
    @Override
    public LoginVO login(LoginRequestDTO loginRequestDTO) {
        //1.查询是否存在用户
        User user = getOne(new QueryWrapper<User>()
                .eq("username", loginRequestDTO.getUsername()));
        if (user == null) {
            throw new CustomException(Message.USER_NOT_FOUND);
        }
        //2.比较密码
        String password = user.getPassword();
        if (!password.equals(DigestUtils.md5DigestAsHex(loginRequestDTO.getPassword().getBytes()))) {
            throw new CustomException(Message.USERNAME_PASSWORD_ERROR);
        }

        //3 检查状态
        if (user.getStatus().equals(AccountStatus.LOCKED)) {
            throw new CustomException(Message.USER_DISABLED);
        }
        //3，生成token
        Date now = new Date();
        //获取三天后的时间
        Date expiresAt = new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000);
        byte[] key = "1234567890".getBytes();

        String token = JWT.create()
                .setPayload("userId", user.getUserId())
                .setExpiresAt(expiresAt)
                .setKey(key)
                .sign();
        UserVO userVO = UserVO.builder()
                .id(user.getUserId())
                .username(user.getUsername())
                .name(user.getName())
                .phone(user.getPhone())
                .gender(user.getGender())
                .role(user.getRole())
                .status(AccountStatus.NORMAL)
                .createTime(user.getCreatedAt())
                .updateTime(user.getUpdatedAt())
                .build();
        return new LoginVO(token, userVO);
    }

    /**
     * 注册
     * @param registerDTO
     */
    public void register(RegisterDTO registerDTO) {
        User user = User.builder()
                .username(registerDTO.getUsername())
                .password(DigestUtils.md5DigestAsHex(registerDTO.getPassword().getBytes()))
                .role(registerDTO.getRole())
                .status(AccountStatus.NORMAL)
                .build();
        save(user);
    }
}
